package net.cityside.summer.web.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.cityside.summer.commons.IDUtil;
import net.cityside.summer.domain.GalleryImg;
import net.cityside.summer.serivce.IGalleryImgService;
import net.cityside.summer.web.security.WebSecurityUtil;
import net.coobird.thumbnailator.Thumbnails;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("gallery/upload")
public class GalleryUploadController {

	private static final Logger logger = Logger
			.getLogger(GalleryController.class);

	@Autowired
	private ServletContext servletContext;

	@Autowired
	private IGalleryImgService galleryImgService;

	@RequestMapping("")
	public String upload() {
		return "upload";
	}

	@RequestMapping(value = "submit", method = RequestMethod.POST)
	public @ResponseBody
	List<Map<String, Object>> uploadSubmit(
			@RequestParam("files[]") MultipartFile img,
			HttpServletRequest request) {
		List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(
				1);
		Map<String, Object> result = new HashMap<String, Object>();
		results.add(result);
		if (img.isEmpty()) {
			result.put("result", "null");
			return results;
		}

		String savedImgName = generateSavedImgName(img.getOriginalFilename());

		try {
			saveImgFile(img, savedImgName);
		} catch (Exception e) {
			return null;
		}

		result.put("name", savedImgName);
		result.put("type", img.getContentType());
		result.put("size", img.getSize());
		result.put("url", servletContext.getContextPath()
				+ "/static/private/gallery/" + savedImgName);
		result.put("thumbnail_url", servletContext.getContextPath()
				+ "/static/private/gallery/" + "s_" + savedImgName);
		return results;
	}

	private void saveImgFile(MultipartFile img, String savedImgName) {
		String savePath = servletContext.getRealPath("/")
				+ "/static/private/gallery/";
		String imgFileName = savePath + savedImgName;
		String thumbnailName = savePath + "s_" + savedImgName;
		File imgFile = new File(imgFileName);

		logger.info("写文件：" + imgFile.getAbsolutePath());
		FileOutputStream fos = null;
		try {
			imgFile.createNewFile();
			fos = new FileOutputStream(imgFile);
			fos.write(img.getBytes());
			fos.flush();
		} catch (FileNotFoundException e) {
			logger.error("文件未找到" + e.getMessage());
			throw new RuntimeException("Save failed");
		} catch (IOException e) {
			logger.error("IO错误", e);
			throw new RuntimeException("Save failed");
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
		}

		try {
			Thumbnails.of(imgFile).size(150, 150).toFile(thumbnailName);
		} catch (Exception e) {
			logger.error("产生缩略图失败", e);
			throw new RuntimeException("Save failed");
		}

		try {
			GalleryImg galleryImg = new GalleryImg(savedImgName,
					WebSecurityUtil.getCurrentUser());
			galleryImgService.save(galleryImg);
		} catch (RuntimeException e) {
			logger.error("记入数据库失败", e);
			throw new RuntimeException("Save failed");
		}
	}

	private static String generateSavedImgName(String initialName) {
		String filename = IDUtil.pureUUID();
		String type = initialName.substring(initialName.lastIndexOf("."));
		return filename + type;
	}

	@RequestMapping(value = "submit", method = RequestMethod.GET)
	public @ResponseBody
	String uploadMagic() {
		return "ok";
	}

	@RequestMapping(value = "title")
	public @ResponseBody
	String saveTitle(@RequestBody List<Map<String, String>> imageTitles) {
		logger.debug(imageTitles);
		List<GalleryImg> imgs = new ArrayList<GalleryImg>(imageTitles.size());

		for (Map<String, String> imageTitle : imageTitles) {
			if (imageTitle.get("img") == null) {
				logger.warn("遇到一个文件名为空的ImageTitle。title="
						+ imageTitle.get("title"));
			} else {
				imgs.add(new GalleryImg(imageTitle.get("img"), imageTitle
						.get("title")));
			}
		}

		logger.info(String.format("请求更新%d个，其中有效请求%d个。", imageTitles.size(),
				imgs.size()));

		galleryImgService.updateTitle(imgs);
		return "ok";
	}
}
